package com.henghai.zhenxuan.ui.page.mine;

import static com.henghai.zhenxuan.data.config.Const.KEY_ADDRESS_PARAMS;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.henghai.zhenxuan.BR;
import com.henghai.zhenxuan.data.api.AddConsigneeInfoApi;
import com.henghai.zhenxuan.data.api.UpdateConsigneeInfoApi;
import com.henghai.zhenxuan.data.bean.AddressBean;
import com.henghai.zhenxuan.data.bean.ConsigneeRepositoryBean;
import com.henghai.zhenxuan.data.repository.DataRepository;
import com.henghai.zhenxuan.domain.event.Messages;
import com.henghai.zhenxuan.domain.message.PageMessenger;
import com.henghai.zhenxuan.utils.Utils;
import com.henghai.zhenxuan.R;
import com.kongzue.dialogx.dialogs.TipDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.kunminx.architecture.ui.page.BaseFragment;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.page.StateHolder;
import com.kunminx.architecture.ui.state.State;
import com.kunminx.architecture.utils.DisplayUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.util.ArrayList;

import cn.qqtheme.framework.entity.City;
import cn.qqtheme.framework.entity.County;
import cn.qqtheme.framework.entity.Province;
import cn.qqtheme.framework.picker.AddressPicker;

/**
 * 新增地址
 */
public class AddAddressFragment extends BaseFragment {
    private AddAddressState mAddAddressState;
    private PageMessenger mMessenger;
    private AddressBean addressBean;
    private static final String TAG = "AddAddressFragment";

    @Override
    protected void initViewModel() {
        mAddAddressState = getFragmentScopeViewModel(AddAddressState.class);
        mMessenger = getApplicationScopeViewModel(PageMessenger.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(com.henghai.zhenxuan.R.layout.fragment_addaddress, BR.vm, mAddAddressState).addBindingParam(BR.click, new ClickProxy());
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        addressBean = (AddressBean) getArguments().getSerializable(KEY_ADDRESS_PARAMS);
        if (addressBean != null) {
            mAddAddressState.contactName.set(addressBean.getConsigneeName());
            mAddAddressState.contactPhone.set(addressBean.getConsigneePhone());
            mAddAddressState.region.set(addressBean.getConsigneeRegion());
            mAddAddressState.address.set(addressBean.getConsigneeAddress());
        }
    }

    public class ClickProxy {
        public void saveAddress() {
            if (TextUtils.isEmpty(mAddAddressState.contactName.get())) {
                ToastUtils.showShort("请输入联系人");
                return;
            }
            if (TextUtils.isEmpty(mAddAddressState.contactPhone.get())) {
                ToastUtils.showShort("请输入手机号");
                return;
            }
            if (TextUtils.isEmpty(mAddAddressState.region.get())) {
                ToastUtils.showShort("请选择区域");
                return;
            }
            if (TextUtils.isEmpty(mAddAddressState.address.get())) {
                ToastUtils.showShort("请输入详细地址");
                return;
            }

            Log.d(TAG, "contactName: " + mAddAddressState.contactName.get() + " contactPhone: " + mAddAddressState.contactPhone.get() + " region:" + mAddAddressState.region.get() + " address:" + mAddAddressState.address.get());
            if (addressBean != null) {
                DataRepository.getInstance().updateConsigneeInfo(getViewLifecycleOwner(), new UpdateConsigneeInfoApi(new
                        ConsigneeRepositoryBean(addressBean.getId(), mAddAddressState.contactName.get(),
                        mAddAddressState.contactPhone.get(),
                        mAddAddressState.region.get(),
                        mAddAddressState.address.get(),
                        addressBean.getIsDefault()
                )), dataResult -> {
                    if (!dataResult.getResponseStatus().isSuccess()) {
                        ToastUtils.showShort(dataResult.getResponseStatus().getResponseCode());
                        return;
                    }
                    mMessenger.input(new Messages(Messages.EVENT_REFRESH_ADDRESS));
                    TipDialog.show("修改成功", WaitDialog.TYPE.SUCCESS);
                    nav().popBackStack();
                });
            } else {
                DataRepository.getInstance().addConsigneeInfo(getViewLifecycleOwner(), new AddConsigneeInfoApi(new
                        ConsigneeRepositoryBean(mAddAddressState.contactName.get(),
                        mAddAddressState.contactPhone.get(),
                        mAddAddressState.region.get(),
                        mAddAddressState.address.get(),
                        "0"
                )), dataResult -> {
                    if (!dataResult.getResponseStatus().isSuccess()) {
                        ToastUtils.showShort(dataResult.getResponseStatus().getResponseCode());
                        return;
                    }
                    mMessenger.input(new Messages(Messages.EVENT_REFRESH_ADDRESS));
                    TipDialog.show("保存成功", WaitDialog.TYPE.SUCCESS);
                    nav().popBackStack();
                });
            }
        }

        //选择区域
        public void selectTheRegion() {
            ArrayList<Province> list = Utils.getInstance().getCityList();
            if (list == null || list.size() == 0) {
                Utils.getInstance().getCityListFromAssets(new Utils.CommonCallback<ArrayList<Province>>() {
                    @Override
                    public void callback(ArrayList<Province> newList) {
                        if (newList != null) {
                            showChooseCityDialog(getActivity(), newList, "", "", "", new AddressPicker.OnAddressPickListener() {
                                @Override
                                public void onAddressPicked(Province province, City city, County county) {
//                                    mAddAddressState.province.set(province);
//                                    mAddAddressState.city.set(city);
//                                    mAddAddressState.district.set(county);
                                    mAddAddressState.region.set(province.getName() + " " + city.getName() + " " + county.getName());
                                }

                            });
                        }
                    }
                });
            } else {
                showChooseCityDialog(getActivity(), list, "", "", "", new AddressPicker.OnAddressPickListener() {
                    @Override
                    public void onAddressPicked(Province province, City city, County county) {
//                        mAddAddressState.province.set(province);
//                        mAddAddressState.city.set(city);
//                        mAddAddressState.district.set(county);
                        mAddAddressState.region.set(province.getName() + " " + city.getName() + " " + county.getName());
                    }
                });
            }
        }

        public void back() {
            nav().popBackStack();
        }
    }


    public static class AddAddressState extends StateHolder {
        public final State<String> region = new State<>("");
        public final State<String> address = new State<>("");
        public final State<String> contactName = new State<>("");
        public final State<String> contactPhone = new State<>("");
    }


    public void showChooseCityDialog(Activity activity, ArrayList<Province> list,
                                     String province, String city, String district, AddressPicker.OnAddressPickListener listener) {
        AddressPicker picker = new AddressPicker(getActivity(), list);
        picker.setTextColor(0xff323232);
        picker.setDividerColor(0xffdcdcdc);
//        picker.setAnimationStyle(R.style.bottom_sheet_anime);
        picker.setCancelTextColor(0xff969696);
        picker.setSubmitTextColor(0xffff6131);
        picker.setTopLineColor(0xfff5f5f5);
        picker.setTopBackgroundColor(0xfff5f5f5);
        picker.setHeight(DisplayUtils.dp2px(250));
        picker.setOffset(5);
        picker.setHideProvince(false);
        picker.setHideCounty(false);
        picker.setColumnWeight(3 / 9.0f, 3 / 9.0f, 3 / 9.0f);
        if (TextUtils.isEmpty(province)) {
            province = "北京市";
        }
        if (TextUtils.isEmpty(city)) {
            city = "北京市";
        }
        if (TextUtils.isEmpty(district)) {
            district = "东城区";
        }
        picker.setSelectedItem(province, city, district);
        picker.setOnAddressPickListener(listener);
        picker.show();
    }
}
